/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.core.pipeline;

import static com.chinamobile.cmss.lakehouse.common.kubernetes.K8sModelConstant.CLUSTER_NAMESPACE_PREFIX;

import com.chinamobile.cmss.lakehouse.common.dto.LakehouseReleaseRequest;
import com.chinamobile.cmss.lakehouse.core.client.InformerClient;
import com.chinamobile.cmss.lakehouse.core.client.InformerException;
import com.chinamobile.cmss.lakehouse.core.deploy.cluster.instance.LakehouseClusterDescriptor;
import com.chinamobile.cmss.lakehouse.core.deploy.cluster.strategy.ClusterDeployStrategyContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class K8sOpsHandler implements CreateHandler<ClusterCreateContext>,
    ReleaseHandler<ClusterReleaseContext>, CheckHandler<ClusterCheckContext> {

    @Autowired
    ClusterDeployStrategyContext clusterDeployStrategyContext;

    @Autowired
    private LakehouseClusterDescriptor lakehouseClusterDescriptor;

    @Autowired
    private InformerClient informerClient;

    @Override
    public boolean handleCreate(ClusterCreateContext context) {
        try {
            clusterDeployStrategyContext.deploy(context.getRequest());
        } catch (Exception e) {
            log.error("deploy :{} failed:{}", context.getRequest(), e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public boolean handleRelease(ClusterReleaseContext context) {
        LakehouseReleaseRequest releaseRequest = context.getReleaseRequest();
        String namespace = releaseRequest.getInstance().replace("_", "-");
        return deleteNamespace(namespace);
    }

    @Override
    public boolean handleCheck(ClusterCheckContext context) {
        // check status
        return lakehouseClusterDescriptor.isRunning(context.getRequest().getInstance().toLowerCase());
    }

    public boolean deleteNamespace(String namespace) {
        try {
            informerClient.deleteNamespace(CLUSTER_NAMESPACE_PREFIX + "-" + namespace);
        } catch (InformerException e) {
            log.error("delete namespace :{} failed:{}", namespace, e.getMessage());
            return false;
        }
        return true;
    }
}
